package com.fjnu.aspect;

import com.fjnu.annotation.QueryPerformanceMonitor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Slf4j
public class PerformanceMonitorAspect {

    @Pointcut("@annotation(queryPerfor)")
    public void allUserSelectMethods(QueryPerformanceMonitor queryPerfor) {}


    @Around("allUserSelectMethods(queryPerfor)")
    public Object monitor(ProceedingJoinPoint joinPoint,
                          QueryPerformanceMonitor queryPerfor ) throws Throwable {

        /**
         * Example 1. 对关键方法的执行性能进行日志监控，
         * 执行时间超过3000ms或配置的timeout，要进行预警。
         */
        long expireTime = queryPerfor.expireTime() ;
        long startTime = System.currentTimeMillis() ;
        Object result = joinPoint.proceed() ;
        long endTime = System.currentTimeMillis() ;
        if (endTime - startTime > expireTime) {
            log.error("[WARNING] the method {} execution time is {} ms, " +
                    " over the expire time {} ms",
                    joinPoint.getSignature().getName(),
                    endTime - startTime,
                    expireTime) ;
        }
        return result ;


    }

}
